package com.wgts.wgts.netmodle;

import android.Manifest;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.util.Base64;
import android.webkit.MimeTypeMap;

import com.wgts.wgts.react.MD5Util;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadListener;
import com.liulishuo.filedownloader.FileDownloader;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.ConnectException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.util.Set;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;



public class DownloadFile {


    private OkHttpClient okHttpClient;

    public DownloadFile(OkHttpClient okHttpClient) {
        this.okHttpClient = okHttpClient;
    }

    public void downFile(final Context context, String url, String localPath, final HttpDownFileCallBack callback) {
        Call call;
        try {
            final SharedPreferences memoryDataInfo = context.getSharedPreferences("httpDownLocalData", 0);

            if (!url.startsWith("http://") && !url.startsWith("https://")) {
                final File doneFile = new File(url.replace("file://", ""));
                ((Activity)context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (callback != null) {
                            callback.onDownLoad(doneFile.length(), doneFile.length(), doneFile.getPath());
                        }
                    }
                });
                return;
            }

            if (localPath == null) {
                localPath = Environment.getExternalStorageDirectory() + "/MoHuDownFiles/" + MD5Util.encrypt(url) + ".apk";
            }

            final String cacheKey = MD5Util.encrypt(url + localPath);

            final File doneFile = new File(localPath);
            if (doneFile.exists()) {//如果存在已经下载完成的文件
                ((Activity)context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (callback != null) {
                            callback.onDownLoad(doneFile.length(), doneFile.length(), doneFile.getPath());
                        }
                    }
                });

                return;
            }

            final File tempFile = new File(localPath + "temp");
            if (!tempFile.getParentFile().exists()) {
                tempFile.getParentFile().mkdirs();
            }

            cancel(cacheKey);//取消之前的请求

            Request.Builder builder = new Request.Builder().tag(cacheKey).url(url);


            //断点下载
            builder.addHeader("RANGE", "bytes=" + String.valueOf(tempFile.length()) + "-");
            call = okHttpClient.newCall(builder.build());
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, final IOException e) {
                    if (e instanceof ConnectException) {
                        callback.onDownFail("请求断开，请检查您的网络连接是否正常！");
                    } else if (e instanceof SocketTimeoutException || e instanceof SocketException) {
                        callback.onDownFail("请求超时，请稍后重试！");
                    } else {
                        callback.onDownFail("请求失败，发生未知错误！");
                    }
                }

                @Override
                public void onResponse(Call call, final Response response) throws IOException {
                    try {
                        final long tempLength = tempFile.length();
                        final long countLength = response.body().contentLength() + tempLength;

                        SharedPreferences.Editor editor = memoryDataInfo.edit();
                        editor.putLong(cacheKey, countLength);
                        editor.commit();

                        RandomAccessFile randomAccessFile = new RandomAccessFile(tempFile, "rwd");
                        randomAccessFile.seek(tempLength);
                        InputStream inputStream = response.body().byteStream();
                        byte[] buffer = new byte[512];
                        int readLength;
                        while ((readLength = inputStream.read(buffer)) != -1) {
                            randomAccessFile.write(buffer, 0, readLength);
                            //下载完毕
                            if (randomAccessFile.length() >= countLength) {
                                tempFile.renameTo(doneFile);
                                doneFile.setWritable(true);
                                doneFile.setReadable(true);
                                doneFile.setExecutable(true);

                            }
                            //是否继续下载
                            if (callback != null && !callback.onDownLoad(countLength, randomAccessFile.length(), doneFile.getPath())) {
                                break;
                            }
                        }
                        if (countLength == -1) {
                            callback.onDownLoad(randomAccessFile.length(), randomAccessFile.length(), doneFile.getPath());
                        }
                        randomAccessFile.close();
                        inputStream.close();
                    } catch (Exception e) {
                        callback.onDownFail("文件下载失败：" + e.getMessage());
                    } finally {
                        if (response != null) {
                            response.close();
                        }
                    }
                }
            });
        } catch (Exception e) {
            callback.onDownFail("文件下载失败：" + e.getMessage());
        }
    }


    public interface HttpDownFileCallBack {
        boolean onDownLoad(long countLength, long downLength, String localPath);

        void onDownFail(String message);
    }


    /**
     * 取消请求
     *
     * @param tag
     */
    public void cancel(String tag) {
        for (Call call : okHttpClient.dispatcher().queuedCalls()) {
            if (call.request().tag().equals(tag))
                call.cancel();
        }
        for (Call call : okHttpClient.dispatcher().runningCalls()) {
            if (call.request().tag().equals(tag))
                call.cancel();
        }
    }


    public static  void installAPK(Context  context, String filePath) {


        String path = Environment.getExternalStorageDirectory() + "/MoHuDownFiles/" + MD5Util.encrypt(filePath) + ".apk";


//        Uri uri = Uri.parse(path);
//
//        if (Build.VERSION.SDK_INT < 23) {
//            Intent intents = new Intent();
//            intents.setAction("android.intent.action.VIEW");
//            intents.addCategory("android.intent.category.DEFAULT");
//            intents.setType("application/vnd.android.package-archive");
//            intents.setData(uri);
//            intents.setDataAndType(uri, "application/vnd.android.package-archive");
//            intents.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            context.startActivity(intents);
//        } else {
//            File file = new File(filePath);
//            if (file.exists()) {
//                openFile(file, context);
//            }
//        }

//        String path = Environment.getExternalStorageDirectory() + "/MoHuDownFiles/" + MD5Util.encrypt(filePath) + ".apk";
//        File file = new File(path);
//
//
//        Intent intent = new Intent();
//        intent.setAction("android.intent.action.VIEW");
//        intent.addCategory("android.intent.category.DEFAULT");
//        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
//        activity.startActivity(intent);






    }



    public static  void openFile(File file, Context context) {
        Intent intent = new Intent();
        intent.addFlags(268435456);
        intent.setAction("android.intent.action.VIEW");
        String type = getMIMEType(file);
        intent.setDataAndType(Uri.fromFile(file), type);
        try {
            context.startActivity(intent);
        } catch (Exception var5) {
            var5.printStackTrace();
            //Toast.makeText(context, "没有找到打开此类文件的程序", Toast.LENGTH_SHORT).show();
        }

    }

    public static  String getMIMEType(File var0) {
        String var1 = "";
        String var2 = var0.getName();
        String var3 = var2.substring(var2.lastIndexOf(".") + 1, var2.length()).toLowerCase();
        var1 = MimeTypeMap.getSingleton().getMimeTypeFromExtension(var3);
        return var1;
    }


    public void downLoad(String url, FileDownloadListener fileDownloadListener){

        String path = Environment.getExternalStorageDirectory() + "/WgtsDownFiles/" + MD5Util.encrypt(url) + ".apk";

        FileDownloader.getImpl().create(url).setPath(path).setForceReDownload(true).setListener(fileDownloadListener).start();
    }

    public void downLoadVideo(String url, String path, FileDownloadListener fileDownloadListener){
        FileDownloader.getImpl().create(url).setPath(path).setForceReDownload(true).setListener(fileDownloadListener).start();
    }


//    new FileDownloadListener() {
//        //等待
//        @Override
//        protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {
//
//        }
//        //下载进度回调
//        @Override
//        protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
//            //progressDialog.setProgress((soFarBytes * 100 / totalBytes));
//        }
//        //完成下载
//        @Override
//        protected void completed(BaseDownloadTask task) {
//            progressDialog.cancel();
//            installAPK();
//        }
//        //暂停
//        @Override
//        protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {
//
//        }
//        //下载出错
//        @Override
//        protected void error(BaseDownloadTask task, Throwable e) {
//            Toast.makeText(ac,"下载出错",Toast.LENGTH_SHORT).show();
//            progressDialog.cancel();
//        }
//        //已存在相同下载
//        @Override
//        protected void warn(BaseDownloadTask task) {
//            progressDialog.cancel();
//        }
//    }




}
